package com.zk.hql.configuration;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author
 * @description
 */
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef ="jpaEntityManagerFactory")
@EnableTransactionManagement
public class JpaConfiguration {
    @Autowired
    @Qualifier("jpaDataSource")
    private DataSource jpaDataSource;


    @Bean(name ="jpaEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        HibernateJpaVendorAdapter japVendor =new HibernateJpaVendorAdapter();
        japVendor.setGenerateDdl(false);
        LocalContainerEntityManagerFactoryBean entityManagerFactory =new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(jpaDataSource);
        entityManagerFactory.setJpaVendorAdapter(japVendor);
        entityManagerFactory.setPackagesToScan("com.zk.hql.entity");
        return entityManagerFactory;
    }
    /**
     * hibernate sessionFactory
     *
     * @return
     * @throws PropertyVetoException
     */
    @Bean(name = "sessionFactory")
    SessionFactory sessionFactory() {
        return entityManagerFactory().getObject().unwrap(SessionFactory.class);
    }

    /**
     * hibernateTemplate
     *
     * @return
     * @throws PropertyVetoException
     */
    @Bean(name = "hibernateTemplate")
    HibernateTemplate hibernateTemplate() {
        HibernateTemplate template = new HibernateTemplate();
        template.setSessionFactory(sessionFactory());
        return template;
    }

    /**
     * 事物管理器
     *
     * @return
     * @throws PropertyVetoException
     */
    @Bean(name = "txManager")
    PlatformTransactionManager txManager() {
        HibernateTransactionManager manager = new HibernateTransactionManager();
        manager.setSessionFactory(sessionFactory());
        return manager;
    }

}

